﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;

namespace ProjectManagement.Web.Common
{
	public class Commom
	{
		//生成验证码的字符串
		public static String CreateValidateString(int len)
		{
			//允许出现的字符----字母和数字
			string chars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

			Random r = new Random(DateTime.Now.Millisecond);
			string ValidateString = "";//存取生成的随机字符串
			for (int i = 0; i < len; i++)
			{
				ValidateString += chars[r.Next(chars.Length)];
			}
			return ValidateString;
		}
		public static byte[] CreateValidateCode(string validatecode)
		{
			//设置场景
			Bitmap bmp = new Bitmap(validatecode.Length * 12, 22);
			//从场景获取绘图对象
			Graphics g = Graphics.FromImage(bmp);
			g.Clear(Color.White);
			//设置绘图参数
			Font font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic);
			RectangleF rf = new RectangleF(0, 0, bmp.Width, bmp.Height);
			LinearGradientBrush brush = new LinearGradientBrush(rf, Color.Red, Color.DarkBlue, 1.2f, true);//设置渐变可变刷子
			Pen pen = new Pen(Color.Silver);//设置绘图的画笔
			//定义随机数
			Random r = new Random(DateTime.Now.Millisecond);
			//绘制干扰线
			for (int i = 0; i < 25; i++)
			{
				int startX = r.Next(bmp.Width);
				int startY = r.Next(bmp.Height);
				int endX = r.Next(bmp.Width);
				int endY = r.Next(bmp.Height);
				g.DrawLine(pen, startX, startY, endX, endY);
			}
			//绘制干扰点
			for (int i = 0; i < 100; i++)
			{
				int x = r.Next(bmp.Width);
				int y = r.Next(bmp.Height);
				int red = r.Next(256);
				int green = r.Next(256);
				int blue = r.Next(256);
				bmp.SetPixel(x, y, Color.FromArgb(red, green, blue));
			}
			//将字符绘制到场景中
			g.DrawString(validatecode, font, brush, 3, 2);
			//创建可用于绘制图片的缓冲区
			MemoryStream ms = new MemoryStream();
			//将图片保存到缓冲区
			bmp.Save(ms, ImageFormat.Jpeg);

			bmp.Dispose();
			return ms.ToArray();
		}
	}
}